// 实习岗位控制器
package org.example.backend.controller;

import jakarta.validation.Valid;
import org.example.backend.dto.InternshipPositionDetailDto;
import org.example.backend.dto.InternshipPositionDto;
import org.example.backend.dto.PageResponseDto;
import org.example.backend.entity.Company;
import org.example.backend.entity.InternshipPosition;
import org.example.backend.entity.User;
import org.example.backend.exception.BusinessException;
import org.example.backend.exception.ResourceNotFoundException;
import org.example.backend.repository.InternshipPositionRepository;
import org.example.backend.service.CompanyService;
import org.example.backend.service.InternshipPositionService;
import org.example.backend.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/internship-positions")
@CrossOrigin
public class InternshipPositionController {

    private static final Logger logger = LoggerFactory.getLogger(InternshipPositionController.class);

    private final InternshipPositionService internshipPositionService;
    private final CompanyService companyService;
    private final UserService userService;
    private final InternshipPositionRepository internshipPositionRepository;

    public InternshipPositionController(InternshipPositionService internshipPositionService,
                                        CompanyService companyService,
                                        UserService userService, InternshipPositionRepository internshipPositionRepository) {
        this.internshipPositionService = internshipPositionService;
        this.companyService = companyService;
        this.userService = userService;
        this.internshipPositionRepository = internshipPositionRepository;
    }

    /**
     * 企业发布实习岗位
     */
    @PostMapping
    @PreAuthorize("hasRole('COMPANY')")
    public ResponseEntity<?> createPosition(@Valid @RequestBody InternshipPositionDto positionDto) {
        try {
            // 获取当前认证用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();

            // 根据用户名获取用户信息
            User user = userService.getUserByUsername(username);

            // 获取企业信息
            Company company = companyService.getCompanyByUserId(user.getId());

            // 发布实习岗位
            InternshipPosition position = internshipPositionService.createPosition(positionDto, company.getId());

            Map<String, Object> response = new HashMap<>();
            response.put("message", "实习岗位发布成功");
            response.put("position", position);

            return ResponseEntity.ok(response);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            logger.error("发布实习岗位失败", e);
            return ResponseEntity.badRequest().body("发布失败：" + e.getMessage());
        }
    }

    /**
     * 企业更新实习岗位
     */
    @PutMapping("/{positionId}")
    @PreAuthorize("hasRole('COMPANY')")
    public ResponseEntity<?> updatePosition(@PathVariable Long positionId,
                                            @Valid @RequestBody InternshipPositionDto positionDto) {
        try {
            // 获取当前认证用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();

            // 根据用户名获取用户信息
            User user = userService.getUserByUsername(username);

            // 获取企业信息
            Company company = companyService.getCompanyByUserId(user.getId());

            // 检查岗位是否属于该企业
            InternshipPosition existingPosition = internshipPositionService.getPositionById(positionId);
            if (!existingPosition.getCompanyId().equals(company.getId())) {
                throw new BusinessException("无权限操作该岗位");
            }

            // 更新实习岗位
            InternshipPosition position = internshipPositionService.updatePosition(positionId, positionDto);

            Map<String, Object> response = new HashMap<>();
            response.put("message", "实习岗位更新成功");
            response.put("position", position);

            return ResponseEntity.ok(response);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            logger.error("更新实习岗位失败", e);
            return ResponseEntity.badRequest().body("更新失败：" + e.getMessage());
        }
    }

    /**
     * 获取实习岗位详情（包含公司名称）
     */
    @GetMapping("/{positionId}")
    public ResponseEntity<?> getPositionWithCompanyInfo(@PathVariable Long positionId) {
        try {
            InternshipPositionDetailDto positionDto = internshipPositionService.getPositionWithCompanyInfo(positionId);
            return ResponseEntity.ok(positionDto);
        } catch (ResourceNotFoundException e) {
            logger.error("获取岗位详情失败", e);
            return ResponseEntity.notFound().build();
        } catch (Exception e) {
            logger.error("获取岗位详情失败", e);
            return ResponseEntity.badRequest().body("获取岗位详情失败：" + e.getMessage());
        }
    }

    /**
     * 企业获取自己发布的实习岗位列表
     */
    @GetMapping("/my")
    @PreAuthorize("hasRole('COMPANY')")
    public ResponseEntity<PageResponseDto<InternshipPosition>> getMyPositions(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            // 获取当前认证用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();

            // 根据用户名获取用户信息
            User user = userService.getUserByUsername(username);

            // 获取企业信息
            Company company = companyService.getCompanyByUserId(user.getId());

            // 获取岗位列表
            Page<InternshipPosition> positionPage = internshipPositionService.getPositionsByCompany(company.getId(), page, size);

            PageResponseDto<InternshipPosition> response = new PageResponseDto<>(
                    positionPage.getContent(),
                    positionPage.getTotalElements(),
                    positionPage.getTotalPages(),
                    page,
                    size
            );

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("获取实习岗位列表失败", e);
            return ResponseEntity.badRequest().body(null);
        }
    }

    /**
     * 删除实习岗位（软删除）
     */
    @DeleteMapping("/{positionId}")
    @PreAuthorize("hasRole('COMPANY')")
    public ResponseEntity<?> deletePosition(@PathVariable Long positionId) {
        try {
            // 获取当前认证用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();

            // 根据用户名获取用户信息
            User user = userService.getUserByUsername(username);

            // 获取企业信息
            Company company = companyService.getCompanyByUserId(user.getId());

            // 检查岗位是否属于该企业
            InternshipPosition existingPosition = internshipPositionService.getPositionById(positionId);
            if (!existingPosition.getCompanyId().equals(company.getId())) {
                throw new BusinessException("无权限操作该岗位");
            }

            // 删除实习岗位
            internshipPositionService.deletePosition(positionId);

            return ResponseEntity.ok("实习岗位删除成功");
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            logger.error("删除实习岗位失败", e);
            return ResponseEntity.badRequest().body("删除失败：" + e.getMessage());
        }
    }

    /**
     * 上线/下线实习岗位
     */
    @PutMapping("/{positionId}/toggle-status")
    @PreAuthorize("hasRole('COMPANY')")
    public ResponseEntity<?> togglePositionStatus(@PathVariable Long positionId) {
        try {
            // 获取当前认证用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();

            // 根据用户名获取用户信息
            User user = userService.getUserByUsername(username);

            // 获取企业信息
            Company company = companyService.getCompanyByUserId(user.getId());

            // 检查岗位是否属于该企业
            InternshipPosition existingPosition = internshipPositionService.getPositionById(positionId);
            if (!existingPosition.getCompanyId().equals(company.getId())) {
                throw new BusinessException("无权限操作该岗位");
            }

            // 切换状态
            InternshipPosition position = internshipPositionService.togglePositionStatus(positionId);

            Map<String, Object> response = new HashMap<>();
            response.put("message", "岗位状态更新成功");
            response.put("position", position);

            return ResponseEntity.ok(response);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            logger.error("更新岗位状态失败", e);
            return ResponseEntity.badRequest().body("状态更新失败：" + e.getMessage());
        }
    }

    /**
     * 分页查询所有实习岗位（供学生浏览）
     */
    @GetMapping
    public ResponseEntity<PageResponseDto<InternshipPositionDetailDto>> getAllPositionsWithCompanyInfo(
            @RequestParam(required = false) String title,
            @RequestParam(required = false) String workLocation,
            @RequestParam(required = false) Integer status,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        // 添加用户身份日志
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String username = auth != null ? auth.getName() : "anonymous";
        String role = auth != null && auth.getAuthorities().iterator().hasNext()
                ? auth.getAuthorities().iterator().next().getAuthority()
                : "no_role";

        logger.info("User {} with role {} accessing internship positions query", username, role);

        try {
            Page<InternshipPositionDetailDto> positionPage =
                    internshipPositionService.getAllPositionsWithCompanyInfo(title, workLocation, status, page, size);

            PageResponseDto<InternshipPositionDetailDto> response = new PageResponseDto<>(
                    positionPage.getContent(),
                    positionPage.getTotalElements(),
                    positionPage.getTotalPages(),
                    page,
                    size
            );

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("获取实习岗位列表失败", e);
            return ResponseEntity.badRequest().body(null);
        }
    }

    /**
     * 管理员上/下线实习岗位
     */
    @PutMapping("/{positionId}/admin-toggle-status")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> adminTogglePositionStatus(@PathVariable Long positionId) {
        try {
            // 管理员可以直接操作，无需检查企业权限
            InternshipPosition position = internshipPositionService.getPositionById(positionId);

            // 切换状态：1(发布中) <-> 0(已下线)
            position.setStatus(position.getStatus() == 1 ? 0 : 1);
            InternshipPosition updatedPosition = internshipPositionRepository.save(position);

            String message = position.getStatus() == 1 ? "实习岗位已上线" : "实习岗位已下线";

            Map<String, Object> response = new HashMap<>();
            response.put("message", message);
            response.put("position", updatedPosition);

            return ResponseEntity.ok(response);
        } catch (ResourceNotFoundException e) {
            return ResponseEntity.notFound().build();
        } catch (Exception e) {
            logger.error("管理员切换实习岗位状态失败", e);
            return ResponseEntity.badRequest().body("操作失败：" + e.getMessage());
        }
    }

}
